package mdm.led.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.BaseController;
import mdm.led.common.Constant;
import mdm.led.entity.User;
import mdm.led.entity.UserApp;
import mdm.led.entity.UserAppPassword;
import mdm.led.log.OperationLog;
import mdm.led.service.UserService;
import mdm.led.util.session.TokenUtil;

@Controller
@RequestMapping(value = "user")
@Api(description = Constant.MODULE_USER)
public class UserController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@ApiOperation(value = "用户查询", notes = "请求参数:<br>" + "pageIndex 页码<br>" + "limit 每页显示条数<br>")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "用户信息列表查询")
	@ResponseBody
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	public AjaxResponse page(@RequestBody User user, @RequestParam("pageSize") Integer pageSize,
			@RequestParam("currPage") Integer currPage) {

		// 开启分页
		Page<User> page = PageHelper.startPage(currPage, pageSize);
		// 需要分页的数据集合
		List<User> users = null;
		try {
			users = userService.selectByCondition(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 需要返回的 map 数据集合
		Map<String, Object> data = new HashMap<String, Object>();
		// 数据
		data.put("inspectorList", users);
		// 当前页
		data.put("currPage", page.getPageNum());
		// 页总数
		data.put("pageCount", page.getPages());
		// 页大小
		data.put("pageSize", page.getPageSize());
		// 总条数
		data.put("totalCount", page.getTotal());

		LOGGER.info("\n-------------- 结果:" + JSON.toJSONString(data) + " ------------");
		return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, data);
	}

	@ApiOperation(value = "用户详情", notes = "请求参数:<br>cUserId  用户id")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "用户详情")
	@ResponseBody
	@RequestMapping(value = "/userDetails", method = RequestMethod.POST)
	public AjaxResponse getUserDetails(@RequestParam("cUserId") int cUserId) {
		User user = new User();
		user.setcUserId(cUserId);
		User result = new User();
		try {
			List<User> users = userService.selectByCondition(user);
			if (users != null) {
				if (users.size() > 0) {
					result = users.get(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
	}

	@ApiOperation(value = "新增用户", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "添加用户")
	@ResponseBody
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public AjaxResponse add(@RequestBody User user, HttpServletRequest request) {
		try {
			if (StringUtils.isEmpty(user.getcUsername()) || StringUtils.isEmpty(user.getcPassword())) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, "", null);
			}
			// 判断用户是否存在
			if (userService.selectByUsername(user.getcUsername()) != null) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, "用戶名已存在", null);
			}
			userService.add(user);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "App新增用户", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "添加用户")
	@ResponseBody
	@RequestMapping(value = "/addUserApp", method = RequestMethod.POST)
	public AjaxResponse addApp(@RequestBody UserApp user, HttpServletRequest request) {
		try {
			if (userService.selectByUsername(user.getcUsername()) != null) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, "用戶名已存在", null);
			}
			userService.addApp(user);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, user);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "修改用户信息", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "修改用户信息")
	@ResponseBody
	@RequestMapping(value = "/modify", method = RequestMethod.PUT)
	public AjaxResponse modify(@RequestBody User user) {
		try {
			LOGGER.info("------------param:{}", user);
			User u = userService.selectByUsername(user.getcUsername());
			if (u != null && !Objects.equals(user.getcUserId(), u.getcUserId())) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, "用户名已存在", null);
			}
			userService.modify(user);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

	@ApiOperation(value = "修改App个人信息", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "修改App个人信息")
	@ResponseBody
	@RequestMapping(value = "/modifyApp", method = RequestMethod.PUT)
	public AjaxResponse modifyApp(@RequestBody UserAppPassword user) {
		try {
			LOGGER.info("------------param:{}", user);
			User u = userService.selectByUsername(user.getcUsername());
			if (u != null && !Objects.equals(user.getcUserId(), u.getcUserId())) {
				return AjaxResponse.reponseBody(Constant.CHECK_CODE, "用户名已存在", null);
			}
			userService.modifyApp(user);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}
	
	@ApiOperation(value = "禁用 / 启用用户 " , notes = "入参 :<br> userID : 用户ID <br> state : >>> 0 :禁用  1 :启用")
	@ResponseBody
	@RequestMapping(value = "updateState",method = RequestMethod.POST)
	public AjaxResponse updateState(@RequestParam("userID")Integer userID,@RequestParam("state") Integer state){
		LOGGER.info("------------userID:{},state:{}", userID,state);
		Integer updateState = userService.updateState(userID, state);
		if(updateState > 0){
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, "修改成功");
		}else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "修改失败");
		}
	}
	
	@ApiOperation(value = "删除用户", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "删除用户")
	@ResponseBody
	@RequestMapping(value = "/deleteUser", method = RequestMethod.PUT)
	public AjaxResponse deleteUser(@RequestParam("cUserId") int cUserId) {
		try {
			User user = new User();
			Short s = 2;
			user.setcUserId(cUserId);
			user.setState(s);
			userService.modify(user);
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, null);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}


	@ApiOperation(value = "App用户查询", notes = "")
	@OperationLog(operationModule = Constant.MODULE_USER, operationFunction = "用户信息列表查询")
	@ResponseBody
	@RequestMapping(value = "/pageApp", method = RequestMethod.POST)
	public AjaxResponse pageApp() {
		try {
			String name = null;
			User user = new User();
			List<User> list = userService.selectByCondition(user);
			if (list.size() > 0) {
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getRoleId() == 3 || list.get(i).getRoleId() == 4 || list.get(i).getRoleId() == 5) {
						String string = list.get(i).getcNickname();
						sb.append(string);
						sb.append(",");
					}
				}
				sb.deleteCharAt(sb.length() - 1);
				name = sb.toString();
			}
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, name);
		} catch (Exception e) {
			LOGGER.error("", e);
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
		}
	}

}
